﻿using Rbac.Domain.Interface;
using Rbac.Domain.Entity;
using Rbac.Domain.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rbac.Domain.Impl
{
	public class RoleRepository : IRoleRepository
	{
		private readonly RbacContext db;
		public RoleRepository(RbacContext db)
		{
			this.db = db;
		}
		/// <summary>
		/// 角色查询
		/// </summary>
		/// <param name="roleName"></param>
		/// <returns></returns>
		public List<Role> SearchRoles(string roleName)
		{
			//IQueryable相当于准备好了sql语句 并未准备数据库
			var roles =db.Roles.Where(c=>c.IsDeleted==false).AsQueryable();
			if(!string.IsNullOrWhiteSpace(roleName))
			{
				roles = roles.Where(c => c.RoleName.Contains(roleName));
			}
			return roles.ToList();
		}
		/// <summary>
		/// 所有角色
		/// </summary>
		/// <returns></returns>
		public IQueryable<Role> GetRoles()
		{
			return db.Roles;
		}
		/// <summary>
		/// 添加
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		/// <exception cref="NotImplementedException"></exception>
		public int Add(Role entity)
		{
			db.Roles.Add(entity);
			return db.SaveChanges();
		}
		/// <summary>
		/// 修改
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		/// <exception cref="NotImplementedException"></exception>
		public int Update(Role entity)
		{
			var role=db.Roles.FirstOrDefault(c => c.RoleId == entity.RoleId);
			role.RoleName= entity.RoleName;
			role.Remark= entity.Remark;
			role.UpdatedTime=DateTime.Now;
			return db.SaveChanges();
		}
		/// <summary>
		/// 删除
		/// </summary>
		/// <param name="idList"></param>
		/// <returns></returns>
		public int Delete(int loginUserId,params int[] idList)
		{
			if(idList.Length<=0)
			{

				return 0;
			}
			var roles=db.Roles.Where(c=>idList.Contains(c.RoleId));
			foreach (var item in roles)
			{
				item.IsDeleted = true;
				item.UpdatedUserId = loginUserId;
				item.UpdatedTime = DateTime.Now;
			}
			return db.SaveChanges();
		}
	}
}
